<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <th:block th:include="include :: header('初始多表格')"/>
</head>
<body class="gray-bg">
<div class="container-div">
  <div class="row">
    <div class="col-sm-12 search-collapse">
      <form id="grid-table-search">
        <div class="select-list">
          <ul>
            <li>
              <div>
                <label>数据源: </label>
                <select name="datasrcId" placeholder="数据源" class="form-control">
                  <option value="">请选择数据源</option>
                  <option th:each="item : ${datasrcList}" th:text="${item.connName}" th:value="${item.id}"></option>
                </select>
              </div>
            </li>
            <li>
              <label>表名称: </label>
              <input type="text" name="tableName"/>
            </li>
            <li>
              <a class="btn btn-primary btn-rounded btn-sm"
                 onclick="$.table.search('grid-table-search', 'grid-table-table')"><i
                  class="fa fa-search"></i>&nbsp;搜索</a>
              <a class="btn btn-warning btn-rounded btn-sm"
                 onclick="$.form.reset('grid-table-search', 'grid-table-table')"><i
                  class="fa fa-refresh"></i>&nbsp;重置</a>
            </li>
          </ul>
        </div>
      </form>
    </div>
    <div class="col-sm-12 search-collapse">
      <form id="grid-table-ext">
        <div class="select-list">
          <ul>
            <li>
              <div>
                <label>生成方案: </label>
                <select name="projectId" placeholder="生成方案" class="form-control">
                  <option value="">请选择生成方案</option>
                  <option th:each="item : ${projects}" th:text="${item.name}" th:value="${item.id}"></option>
                </select>
              </div>
            </li>
          </ul>
        </div>
      </form>
    </div>
    <div class="btn-group-sm" id="grid-table-toolbar" role="group">
      <a class="btn btn-success multiple disabled" onclick="batchGenCode()">
        <i class="fa fa-plus"></i> 生成
      </a>
      <a class="btn btn-success " onclick="createTable()">
        <i class="fa fa-plus"></i> 创建
      </a>
      <a class="btn btn-info" onclick="importTable()">
        <i class="fa fa-plus"></i> 导入
      </a>
      <a class="btn btn-primary single disabled" onclick="$.operate.edit()">
        <i class="fa fa-edit"></i> 修改
      </a>
      <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()">
        <i class="fa fa-remove"></i> 删除
      </a>
    </div>
    <div class="col-xs-12 select-table table-striped">
      <table id="grid-table-table"></table>
    </div>
  </div>
</div>

<div th:include="include :: footer"></div>
<div th:include="include :: bizdk"></div>
</body>
<script th:src="@{/ajax/libs/highlight/highlight.min.js}"></script>
<script th:inline="javascript">
var prefix = ctx + "gen/table";

$(function() {
		var options = {
				id: "grid-table-table",
				formId: "grid-table-search",
				toolbar: "grid-table-toolbar",
				url: prefix + "/page",
				createUrl: prefix + "/add",
				removeUrl: prefix + "/delete",
				updateUrl: prefix + "/edit/{id}",
				modalName: "表格",
				responseHandler: bizdk.pageResponseHandler,
						columns: [{
						checkbox: true
				},
				{
						field : 'id',
						title : 'ID'
				},
								{
						field : '',
						title : '数据源'
				},
				{
						field : 'tableName',
						title : '表名'
				},
				{
						field : 'beanName',
						title : 'bean名称'
				},
				{
						field : 'tableComment',
						title : '表备注'
				},
				{
						title: '操作',
						width: '300px',
						align: 'center',
						formatter: function(value, row, index) {
								var actions = [];
								actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="$.operate.edit(' + row.id + ')"><i class="fa fa-edit"></i>编辑</a> ');
								actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="syncTable(' + row.id + ')"><i class="fa fa-edit"></i>同步</a> ');
                actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="preview(' + row.id + ')"><i class="fa fa-edit"></i>预览</a> ');
								actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="genCode(' + row.id + ', \'' + row.tableName + '\')"><i class="fa fa-edit"></i>生成代码</a> ');
								actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(' + row.id + ')"><i class="fa fa-remove"></i>删除</a>');
								return actions.join('');
						}
				}]
		};
		$.table.init(options);
});


// 批量生成代码
function batchGenCode() {
    var tableIds = $.table.selectColumns("id");
    if (tableIds.length == 0) {
        $.modal.alertWarning("请选择要生成的数据");
        return;
    }
    genCode(tableIds);
}

function genCode(tableIds) {
    var data = $("#grid-table-ext").serializeObject();
    if (!data.projectId || data.projectId < 1){
        $.modal.alertError("请选择生成方案");
        return;
    }
    if (Array.isArray(tableIds)){
        data.tableIds = tableIds;
    } else {
        data.tableIds = [];
        data.tableIds.push(tableIds)
    }

    var genUrl = ctx + "gen/generator/code"
    $.ajax({
        type: "POST",
        url: genUrl,
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(data),
        async: false,
        error: function (req) {
            console.log(req);
            $.modal.alertError("系统错误");
        },
        success: function (data) {
            $.operate.successCallback(data);
        }
    });
}

// 导入表结构
function importTable() {
	var importTableUrl = prefix + "/importTable";
	$.modal.open("导入表结构", importTableUrl);
}

// 创建表结构
function createTable() {
	var creatTableUrl = prefix + "/createTable";
	$.modal.open("创建表结构", creatTableUrl);
}

// 预览代码
function preview(tableId) {
    var data = $("#grid-table-ext").serializeObject();
    if (!data.projectId || data.projectId < 1){
        $.modal.alertError("请选择生成方案");
        return;
    }

    var preViewUrl = ctx + "gen/generator/preview?tableId="+tableId+"&projectId="+data.projectId;
    $.modal.loading("正在加载数据，请稍候...");
    $.get(preViewUrl, function(result) {
        if (result.code == web_status.SUCCESS) {
            var items = [];
            $.each(result.data, function(index, value) {
                var templateName = index.substring(index.lastIndexOf("/") + 1, index.length).replace(/\.vm/g, "");
                var codeName = templateName.replace(".", "");
                var language = templateName.substring(templateName.lastIndexOf(".") + 1);
                var highCode = "";
                try{
                  highCode = hljs.highlight(language, value).value;
                } catch (error) {
                  highCode = hljs.highlightAuto(value).value;
                }
                items.push({
                    title: templateName ,
                    content: "<pre class=\"layui-code\"><a style=\"float:right\" href=\"javascript:copyText('" + codeName + "')\"><i class=\"fa fa-copy\"></i> 复制</a><code id=\"" + codeName + "\">" + highCode + "</code></pre><textarea id=\"t_" + codeName + "\" style='position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;'></textarea><script>function copyText(codeName){var text = document.getElementById(codeName).innerText;var input = document.getElementById(\"t_\"+codeName);input.value = text;input.select();document.execCommand(\"copy\");$.modal.msgSuccess(\"复制成功\");}<\/script>"
                })
            });
            top.layer.tab({
                area: ['90%', '90%'],
                shadeClose: true,
                success: function(layero, index){
                    parent.loadCss(ctx + "ajax/libs/highlight/default.min.css");
                },
                tab: items
            });
        } else {
            $.modal.alertError(result.msg);
        }
        $.modal.closeLoading();
    });
}

function syncTable(tableId) {
    var preViewUrl = prefix + "/sync/"+tableId;
    $.modal.loading("正在同步数据，请稍候...");
    $.get(preViewUrl, function(result) {
        if (result.code == web_status.SUCCESS) {
        
        } else {
            $.modal.alertError(result.msg);
        }
        $.modal.closeLoading();
    });
}


</script>
</html>